﻿using System;
using System.Data;
using System.Collections .Generic;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Rison.BusinessFacade.Common;
using Rison.BusinessFacade.Helper;

namespace Rison.Web.Common
{
    public abstract class PageDataViewBase : PageBase
    {
        protected int CheckBoxIndex = 0;
        protected FacadeBase baseFacade = null;
        protected string editPage = string.Empty;
        protected Button addButton = null;
        protected Button deleteButton = null;
        protected GridView dataView = null;
        protected Panel pnlConditions = null;
        protected Label labMessage = null;
        protected HtmlInputHidden hidCurrentPageIndex = null;
        
        protected PageDataViewBase()
            : base()
        {
            base.Load += new EventHandler(Page_Load);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            //CurrentLoginedUser.SetCurrentUserId("admin", "888888");

            if (!this.IsPostBack)
            {
                if (deleteButton != null)
                    SetDeleteButtonAlerter(deleteButton);

                InitConditions();
            }
            else if (hidCurrentPageIndex != null && hidCurrentPageIndex.Value != "")
            {
                this.GetPageIndex();
                this.BindData();
            }
            
        }

        protected void SetDeleteButtonAlerter(Button deleteButton)
        {
            deleteButton.Attributes.Add("OnClick", "javascript:return window.confirm('确定删除选择的数据吗？');");
        }

        protected virtual void BindData()
        {
            if (dataView != null)
            {
                DataSet data = GetDataSource();

                rowNumber = data.Tables[0].Rows.Count;

                this.dataView.DataSource = data;
                this.dataView.PageIndex = currentPageIndex;
                this.dataView.DataBind();

                pageCount = dataView.PageCount;

                if (dataView.Rows.Count == 0)
                    if (labMessage != null)
                        labMessage.Text = "当前尚无数据，请添加。";

                data.Dispose(); data = null; 
            }
        }

        protected virtual DataSet GetDataSource()
        {
            DataSet data = null;

            List<Condition> conditions = this.GetConditions();
            if (conditions != null && conditions.Count > 0)
                data = baseFacade.GetDataBy(conditions);
            else
                data = baseFacade.GetAllData();

            return data;
        }

        protected virtual void InitConditions()
        {
        }

        protected void gvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.currentPageIndex = e.NewPageIndex;
            this.BindData();
        }

        protected virtual void btnAppend_Click(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty (editPage))
                this.Response.Redirect(editPage);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.currentPageIndex = 0;
            BindData();
        }


        #region "  读取页面中的查询条件  "
        protected virtual List<Condition> GetConditions()
        {
            List<Condition> conditions = null;
            if (pnlConditions != null)
            {
                conditions = new List<Condition>();
                foreach (Control c in pnlConditions.Controls)
                {
                    if (c.GetType().Name == "DropDownList")
                    {
                        if ((c as DropDownList).SelectedItem != null)
                            if (!"全部".Equals((c as DropDownList).SelectedItem.Text) && !string.IsNullOrEmpty((c as DropDownList).SelectedItem.Text.Trim()))
                                conditions.Add(new Condition((c as DropDownList).DataValueField, (c as DropDownList).SelectedValue));
                    }
                }
            }

            return conditions;
        }
        #endregion


        #region "  取得被勾选的行的行索引集合  "
        /// <summary>
        /// 取得被勾选的行的行索引集合。
        /// </summary>
        /// <returns></returns>
        protected virtual List<int> GetSelectedItemsIndex()
        {
            List<int> items = null;
            if (dataView != null)
            {
                items = new List<int>();
                foreach (GridViewRow row in dataView.Rows)
                {
                    foreach (Control c in row.Cells[CheckBoxIndex].Controls)
                    {
                        if (c.GetType().Name == "CheckBox")
                        {
                            if ((c as CheckBox).Checked)
                            {
                                items.Add(row.RowIndex);
                            }
                        }
                    }
                }
            }

            return items;
        }
        #endregion


        #region "  删除  "
        /// <summary>
        /// 这里暂时只考虑存在identity主键的情况，并逐行直接删除。
        /// 若要使用事务，则需重写该方法。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void btnDelete_Click(object sender, EventArgs e)
        {
            string msg = string.Empty;
            List<int> selectedItems = null;

            if (dataView == null || dataView.DataKeys.Count == 0)
                msg = "空数据，无法删除！";
            else if (baseFacade == null)
                msg = "未知的删除对象方法，请检查！";
            else
            {
                selectedItems = this.GetSelectedItemsIndex();
                if (selectedItems == null || selectedItems.Count == 0)
                    msg = "请勾选要删除的数据行！";
                else
                {
                    List<string> cannotDeleteKeys = this.GetCannotDeleteKeyValueOrName();
                    foreach (int index in selectedItems)
                    {
                        if (cannotDeleteKeys != null && cannotDeleteKeys.Contains(dataView.DataKeys[index].Value.ToString()))
                            msg = "第(" + (index + 1).ToString() + ")行为系统内置数据，不能删除！";
                        else if (baseFacade.Delete(Convert.ToInt64(dataView.DataKeys[index].Value)) < 0)
                        {
                            msg = "删除错误！";
                            break;
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(msg))
                msg = "删除完成！成功删除" + selectedItems.Count.ToString() + "行数据。";

            BindData();

            if (labMessage != null) labMessage.Text = msg;
            else Response.Write("<span style='color:red'>" + msg + "</span>");
        }

        //系统内置的不可删除的数据的主键值或名称，如系统用户(1,admin)
        protected virtual List<string> GetCannotDeleteKeyValueOrName()
        {
            return null;
        }
        #endregion


        #region "  分页  "
        protected int currentPageIndex
        {
            get { return (ViewState["CurrentPageIndex"] == null) ? 0 : Convert.ToInt32(ViewState["CurrentPageIndex"]); }
            set { ViewState["CurrentPageIndex"] = value; }
        }

        protected int rowNumber
        {
            get { return (ViewState["rowNumber"] == null) ? 0 : Convert.ToInt32(ViewState["rowNumber"]); }
            set { ViewState["rowNumber"] = value; }
        }

        protected int pageCount
        {
            get { return (ViewState["pageCount"] == null) ? 0 : Convert.ToInt32(ViewState["pageCount"]); }
            set { ViewState["pageCount"] = value; }
        }

        protected virtual void GetPageIndex()
        {
            if (hidCurrentPageIndex != null)
            {
                if (this.hidCurrentPageIndex.Value == "p")
                {
                    currentPageIndex -= 1; if (currentPageIndex < 0) currentPageIndex = 0;
                }
                else if (this.hidCurrentPageIndex.Value == "n")
                {
                    currentPageIndex += 1; if (currentPageIndex > pageCount - 1) currentPageIndex = pageCount - 1;
                }
                else if (dataView != null && dataView.BottomPagerRow != null && dataView.BottomPagerRow.Controls.Count > 0)
                {
                    foreach (Control c in dataView.BottomPagerRow.Controls[0].Controls)
                    {
                        if (c.GetType().Name.Equals("TextBox"))
                        {
                            if (StringHelper.IsNumber((c as TextBox).Text))
                            {
                                currentPageIndex = Convert.ToInt32((c as TextBox).Text) - 1;
                                if (currentPageIndex < 0) currentPageIndex = 0;
                                if (currentPageIndex > pageCount - 1) currentPageIndex = pageCount - 1;
                            }
                            break;
                        }
                    }
                }

                hidCurrentPageIndex.Value = string.Empty;
            }
        }


        protected void gvData_OnDataBound(object sender, EventArgs e)
        {
            if (dataView.BottomPagerRow != null && dataView.BottomPagerRow.Controls.Count > 0)
            {
                foreach (Control c in dataView.BottomPagerRow.Controls[0].Controls)
                {
                    if (c.GetType().Name.Equals("Label"))
                    {
                        if (c.ID.IndexOf("labRowCount") >= 0)
                        {
                            (c as Label).Text = rowNumber.ToString();
                        }
                        else if (c.ID.IndexOf("labCurrentPage") >= 0)
                        {
                            (c as Label).Text = (currentPageIndex + 1).ToString();
                        }
                        else if (c.ID.IndexOf("labPageCount") >= 0)
                        {
                            (c as Label).Text = dataView.PageCount.ToString();
                        }
                    }
                }
            }
        }
        #endregion

    }
}
